package com.wh.springboot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.springboot.common.entity.User;
import com.wh.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import com.wh.springboot.common.Result;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.wh.springboot.service.IHesuanService;
import com.wh.springboot.common.entity.Hesuan;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author elsy
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/hesuan")
public class HesuanController {
    @Resource
    private IHesuanService hesuanService;
    @Resource
    private IUserService userService;

    // 新增和修改
    @PostMapping
    public Result save(@RequestBody Hesuan hesuan) {
        //新增或者更新
        return Result.success(hesuanService.saveOrUpdate(hesuan));
    }

    //  查询所有数据
    @GetMapping
    public Result findAll() {
        return Result.success(hesuanService.list());
    }

    //根据用户id查询
    @GetMapping("/{userId}")
    public Result findOne(@PathVariable Integer userId) {
        List<Hesuan> hesuanList = hesuanService.findByUserId(userId);
        return Result.success(hesuanList);
    }

    //删除数据
    @DeleteMapping("/{id}")//id 与下面的id必须一致
    //    @PathVariable 表示 url 这个参数
    public Result delete(@PathVariable Integer id) {
        return Result.success(hesuanService.removeById(id));
    }

    //批量删除
    @DeleteMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(hesuanService.removeByIds(ids));
    }

    //分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String username) {
        QueryWrapper<Hesuan> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        Page<Hesuan> page = hesuanService.findPage(new Page<>(pageNum, pageSize), username);
        for (Hesuan hesuan : page.getRecords()) {
            if (hesuan.getUid() != null) {
                User user = userService.getById(hesuan.getUid());
                hesuan.setUsername(user.getUsername());
                hesuan.setNickname(user.getNickname());
                hesuan.setPhone(user.getPhone());
                hesuan.setCard(user.getCard());
            }
        }
        return Result.success(page);
    }
}

